import request from '@/utils/request'
import { getToken } from '@/utils/auth'


// 智普问答
export function petChat(diaryData, onProgress) {
    return new Promise((resolve, reject) => {
        const url = '/dev-api/zhipu/feedback';
        const token = getToken();

        // 创建中止控制器和超时机制
        const controller = new AbortController();
        const timeoutId = setTimeout(() => {
            controller.abort();
            reject(new Error('请求超时，30秒内未收到响应'));
        }, 30000); // 30秒超时

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(diaryData),
            signal: controller.signal // 绑定中止信号
        })
            .then(response => {
                clearTimeout(timeoutId); // 清除超时定时器
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                if (!response.body) {
                    throw new Error('响应不包含可读流');
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let buffer = '';
                let fullFeedback = '';

                function processEvents(events) {
                    events.forEach(eventText => {
                        const lines = eventText.split('\n');
                        let eventData = '';
                        lines.forEach(line => {
                            if (line.startsWith('data:')) {
                                eventData += line.slice(5).trim();
                            }
                        });
                        if (eventData && eventData !== '[DONE]') {
                            fullFeedback += eventData;
                            // 实时回调
                            if (typeof onProgress === 'function') {
                                onProgress(fullFeedback);
                            }
                        }
                    });
                }

                function read() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            resolve(fullFeedback);
                            return;
                        }
                        buffer += decoder.decode(value, { stream: true });
                        const events = buffer.split(/\n\n/);
                        buffer = events.pop() || '';
                        processEvents(events);
                        read();
                    }).catch(reject);
                }

                read();
            })
            .catch(error => {
                clearTimeout(timeoutId); // 确保清除定时器
                if (error.name === 'AbortError') {
                    reject(new Error('请求已被中止，可能是超时或用户取消'));
                } else {
                    reject(error);
                }
            });
    });
}
